package org.yxjme.exbluetoothserver;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tv_msg ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindService();
    }


    public void bindService(){
        Intent bindIntent = new Intent(this, BluetoothServer.class);
        bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            tv_msg = findViewById(R.id.tv_msg);
            tv_msg.setText(new StringBuffer().append(msg.obj.toString()).append("\n"));
            LogUtil.v("[接收到的信息]->" + msg.obj);
        }
    };


    private ServiceConnection serviceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ((BluetoothServer.MyBinder) service).init(handler);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }
}